

from rest_framework import serializers
from orders.models import OrderInfo,OrderGoods
from goods.models import SKU

# ===========嵌套序列化OrderGoods自定义序列化器=========
class SKUSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = [
            'name',
            'default_image' # ImageField类型字段序列化结果为其url属性(url属性就是完整的图片链接)
        ]

# ===========嵌套序列化OrderGoods自定义序列化器=========
class OrderGoodsSerializer(serializers.ModelSerializer):

    # sku是一个外键关联字段，记录关联的主表SKU单一对象
    sku = SKUSimpleSerializer()

    class Meta:
        model = OrderGoods
        fields = [
            'count',
            'price',
            'sku'
        ]

# ===========订单对象详情序列化=========
class OrderInfoDetailSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField()

    # skus 隐藏字段，记录关联的多个OrderGoods模型类对象
    skus = OrderGoodsSerializer(many=True)

    class Meta:
        model = OrderInfo
        fields = [
            'order_id',
            'user',
            'total_count',
            'total_amount',
            'freight',
            'pay_method',
            'status',
            'create_time',

            'skus' # OrderInfo模型类中无显示定义的skus字段，那么该字段很有可能是从表隐藏字段
        ]

    # 针对status字段单独自定义校验
    def validate_status(self, value):
        if value not in [1,2,3,4,5,6]:
            return serializers.ValidationError('状态不合法')
        return value


# ===========订单对象简单序列化=========
class OrderInfoModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderInfo
        fields = [
            'order_id',
            'create_time'
        ]